# -*- encoding=utf8 -*-
from django.core.cache import cache
from django.shortcuts import render

from apps.assetmgnt.controler import reboot
from utils.decorators import service_required
from apps.auditconf.controler import a4_reboot
from utils.viewutil import savelog, ajaxresponse
from apps.assetmgnt.models import Device, DevType
from apps.assetmgnt.controler import firewall2_token
from apps.firewallV2.controler import reboot_T3_v2_api
from apps.new_a4.controler import new_a4_base_requests
from apps.a4api.controler import a4_api_reboot, audit_token
from apps.log_audit.controler import log_audit_base_requests
from apps.ids.controler import ids_base_requests, token_valid
from apps.firewall3_1.controler import firewall3_token, reboot_T3_v3_api


@service_required('sys_config')
def pathch_operation(request):
    """进入批量处理页面"""
    """批量管理页面去除跳转设备"""
    jump_types = DevType.objects.filter(
        ename__in=('fortress_machine', 'fortress_machine_V2', 'fortress_machine_base', 'next_filrewall')
    ).values_list('id', flat=True)
    jump_types = tuple([type_id for type_id in jump_types])
    devs = Device.objects.exclude(dtype_id__in=jump_types).all()
    return render(request, 'patchoperat.html', {'devs': devs})


def reboot_all_devs(request):
    """重启所有设备"""
    dtype = int(request.GET.get('dtype', 0))
    ids = request.GET.get('ids', '')
    ids = ids.split(',')

    if dtype == 0:
        devs = Device.objects.all()
        for dev in devs:
            curip = dev.ip
            dtyid = dev.dtype_id
            devename = DevType.objects.get(id=dtyid).ename
            if devename == "T3-2.0" or devename == "T3-3.0" or devename == "T3-5.0":
                tokendata = firewall2_token(curip, devversion=devename)
                params = {
                    "method": "reboot",
                }
                res = reboot_T3_v2_api(ip=curip, params=params, tokendata=tokendata, devversion=devename)
            elif devename == "T3-3.1":
                tokendata = firewall3_token(curip)
                params = {
                    "method": "reboot",
                }
                res = reboot_T3_v3_api(ip=curip, params=params, tokendata=tokendata)
            elif devename == "A4-3.0":
                token = cache.get("%s+new_a4_token" % curip)
                if token:
                    cache.delete("%s+new_a4_token" % curip)
                new_a4_base_requests(curip, addr='/api/api_v1/config/reboot/')
            elif devename == "A4":
                a4_reboot(curip, '/system/restart/')
            elif devename == "A4Api":
                tokenvl = audit_token(curip)
                a4_api_reboot(curip, tokendata=tokenvl)
            elif devename == "LAS":
                # reboot_las_api(curip)
                log_audit_base_requests(ip=curip, addr=f"/api/shutdownOrrestart/reboot",
                                        data={'execType': 'reboot'},
                                        method="post")
            elif devename == 'IDS':
                addr = f'/api/reboot?api_key={dev.username}&lang=cn'
                ids_base_requests(curip, addr, data={'operation': '0'}, method='put')
            else:
                res = reboot(dev.ip, devename)
    else:
        for id in ids:
            try:
                dev = Device.objects.get(id=id)
                dtypid = dev.dtype_id
                curip = dev.ip
                devename = DevType.objects.get(id=dtypid).ename
                if devename == "T3-2.0" or devename == "T3-3.0" or devename == "T3-5.0":
                    tokendata = firewall2_token(curip, devversion=devename)
                    params = {
                        "method": "reboot",
                    }
                    res = reboot_T3_v2_api(ip=curip, params=params, tokendata=tokendata, devversion=devename)
                elif devename == "T3-3.1":
                    tokendata = firewall3_token(curip)
                    params = {
                        "method": "reboot",
                    }
                    res = reboot_T3_v3_api(ip=curip, params=params, tokendata=tokendata)
                elif devename == "A4-3.0":
                    token = cache.get("%s+new_a4_token" % curip)
                    if token:
                        cache.delete("%s+new_a4_token" % curip)
                    new_a4_base_requests(curip, addr='/api/api_v1/config/reboot/')
                elif devename == "A4":
                    a4_reboot(curip, '/system/restart/')
                elif devename == "A4Api":
                    tokendata = audit_token(curip)
                    a4_api_reboot(curip, tokendata=tokendata)
                elif devename == "LAS":
                    log_audit_base_requests(
                        ip=curip,
                        addr=f"/api/shutdownOrrestart/reboot",
                        data={'execType': 'reboot'},
                        method="post")
                elif devename == 'IDS':
                    addr = f'/api/reboot?api_key={dev.username}&lang=cn'
                    ids_base_requests(curip, addr, data={'operation': '0'}, method='put')
                else:
                    res = reboot(dev.ip, devename)
            except Exception:
                pass
    return ajaxresponse({'head': 'OK', 'body': u'设备重启成功', 'redirect': '/assetmgnt/batch/?tabName=tab3'})
